/*
 * LicenseDialog.java
 *
 * Created on October 26, 2008, 2:58 PM
 */

package sk.yw.azetclient.gui;

import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutionException;
import javax.swing.SwingWorker;
import org.apache.log4j.Logger;
import sk.yw.azetclient.Main;
import sk.yw.azetclient.gui.actions.ExitAction;

/**
 *
 * @author  error216
 */
public class LicenseDialog extends javax.swing.JDialog {
    
    private static final Logger logger = Logger.getLogger(LicenseDialog.class);
    
    private static final String LICENSE_LOCATION =
            "sk/yw/azetclient/COPYING";
    
    private WindowListener exitApplicationOnCloseListener =
            new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {            
            (new ExitAction()).actionPerformed(
                    new ActionEvent(e.getSource(),
                                    ActionEvent.ACTION_PERFORMED,
                                    "exit"));
        }
    };
    
    private SwingWorker<String,Boolean> licenseLoadingWorker =
            new SwingWorker<String,Boolean>() {

        @Override
        protected String doInBackground() throws Exception {
            StringBuilder builder = new StringBuilder();
        
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    ClassLoader.getSystemResourceAsStream(LICENSE_LOCATION)));
            try {
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                    builder.append('\n');
                }
            } catch (IOException ex) {
                logger.error("Unable to read license agreement.", ex);
            } finally {
                try {
                    reader.close();
                } catch (IOException ex) {
                    logger.error("Unable to read license agreement", ex);
                }
            }

            return builder.toString();
        }
        
        @Override
        protected void done() {
            try {
                licenseTextArea.setText(get());
                licenseTextArea.setCaretPosition(0);
                licenseScrollPane.getViewport().setViewPosition(
                        new Point(0,0));
            } catch (InterruptedException ex) {
                logger.error("Unable to read license agreement", ex);
            } catch (ExecutionException ex) {
                logger.error("Unable to read license agreement", ex);
            }
        }
    };
    
    /** Creates new form LicenseDialog */
    public LicenseDialog(java.awt.Frame parent) {
        super(parent, true);
        initComponents();
        setLocationRelativeTo(null);
        addWindowListener(exitApplicationOnCloseListener);
        licenseLoadingWorker.execute();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        licenseScrollPane = new javax.swing.JScrollPane();
        licenseTextArea = new javax.swing.JTextArea();
        exitButton = new javax.swing.JButton();
        agreeButton = new javax.swing.JButton();
        licenseLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(Main.getText("licenseDialog.title"));

        licenseTextArea.setColumns(20);
        licenseTextArea.setEditable(false);
        licenseTextArea.setRows(5);
        licenseTextArea.setText(Main.getText("licenseDialog.loading"));
        licenseScrollPane.setViewportView(licenseTextArea);

        exitButton.setAction(new ExitAction());

        agreeButton.setText(Main.getText("licenseDialog.agree"));
        agreeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                agreeButtonActionPerformed(evt);
            }
        });

        licenseLabel.setText(Main.getText("licenseDialog.label"));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(licenseScrollPane, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 457, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(exitButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(agreeButton))
                    .addComponent(licenseLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 457, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(licenseLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(licenseScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 352, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(agreeButton)
                    .addComponent(exitButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void agreeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_agreeButtonActionPerformed
    Main.setProperty("azetclient.license.agreed","true");
    
    (new Thread() {
            @Override
        public void run() {
            Main.saveProperties();
        }
    }).start();
    
    dispose();
}//GEN-LAST:event_agreeButtonActionPerformed
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton agreeButton;
    private javax.swing.JButton exitButton;
    private javax.swing.JLabel licenseLabel;
    private javax.swing.JScrollPane licenseScrollPane;
    private javax.swing.JTextArea licenseTextArea;
    // End of variables declaration//GEN-END:variables
    
}
